<?php
/*
 LICENSE

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License (GPL)
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

 To read the license please visit http://www.gnu.org/copyleft/gpl.html
*/

/* Konfiguracja. */
require_once('./config.inc');

/* Wymagane biblioteki. */
require_once('./lastRSS.php');

/* *ślurp */
$parser = new lastRSS();
$parser->CDATA = 'content';
$feed = $parser->Get($rssUrl);

/* Identyfikator ostatnio wysłanego elementu kanału RSS. */
$lastGuid = '';
if (file_exists('rss2blip.dat'))
{
	$lastGuid = file_get_contents('rss2blip.dat');
}

$lastGuidToSave = $lastGuid;

$items = count($feed['items']);
$itemsToBlip = array();

for ($i = $items - 1; $i >= 0; $i--)
{
	if ($lastGuid != '')
	{
		/* Ten element był już publikowany - usuwamy z tablicy wszystkie starsze elementy. */
		if ($lastGuid == $feed['items'][$i]['guid'])
		{
			$itemsToBlip = array();
		}
		else
		{
			$itemsToBlip[] = $feed['items'][$i];
		}
	}
	else
	{
		$itemsToBlip[] = $feed['items'][$i];
	}
	
	$lastGuidToSave = $feed['items'][$i]['guid'];
}

if (count($itemsToBlip > 0))
{
	foreach ($itemsToBlip as $itemToBlip)
	{	
		postToBlip($blipUser,$blipPassword, mb_substr($itemToBlip['link'] . ' ' . iconv($feed['encoding'], 'UTF-8', $itemToBlip['title']), 0, 160));
	}
}

file_put_contents('rss2blip.dat', $lastGuidToSave);

function postToBlip($username, $password, $message)
{
	$curl = curl_init('http://api.blip.pl/updates');
	
	curl_setopt($curl, CURLOPT_USERAGENT, 'rss2blip');
	curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-blip-api: 0.02', 'Accept: application/json'));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, 'body=' . urlencode($message));

	curl_exec($curl);
}

?>